<?php
/**********************************************************************************
WIKINDX: Bibliographic Management system.
Copyright (C)

This program is free software; you can redistribute it and/or modify it under the terms
of the GNU General Public License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program;
if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA

The WIKINDX Team 2007
sirfragalot@users.sourceforge.net
**********************************************************/
/*****
*	CONFIG administration class
*
*	$Header: /cvsroot/wikindx/wikindx3/core/admin/CONFIG.php,v 1.14 2007/04/12 11:49:33 sirfragalot Exp $
*****/
class CONFIG
{
// Constructor
	function CONFIG($db)
	{
		$this->db = $db;
		include_once("core/messages/MESSAGES.php");
		$this->messages = new MESSAGES();
		include_once("core/messages/SUCCESS.php");
		$this->success = new SUCCESS();
		include_once("core/messages/ERRORS.php");
		$this->errors = new ERRORS();
		include_once("core/html/FORM.php");
		include_once("core/html/MISC.php");
		// Start the templating system
		include_once("core/template/TEMPLATE.php");
		$this->template = new TEMPLATE('content');
		$this->fields = array("title", "contactEmail", "description", "fileDeleteSeconds",
			"paging", "pagingMaxLinks", "stringLimit", "language", "style", "template",
			"multiUser", "userRegistration", "notify", "imgWidthLimit", "imgHeightLimit", "maxPaste", 
			"fileAttach", "fileViewLoggedOnOnly", "lastChanges", "lastChangesType", "importBib", 
			"emailNews", "lastChangesDayLimit", "emailNewRegistrations", "registrationModerate",);
	}
// Interface to configure WIKINDX
	function displaySetup($error = FALSE, $update = FALSE)
	{
		include("config.php");
		include_once("core/session/SESSION.php");
		$session = new SESSION();

		if(!$session->getVar("setup_superadmin"))
		{
			include_once("core/authorize/AUTHORIZE.php");
			$authorize = new AUTHORIZE($this->db);
			if($pString = $authorize->initLogon())
				return $pString;
		}

		include_once("core/messages/LANGUAGE.php");
		$language = new LANGUAGE();
		include_once("core/html/HTML.php");
		$html = new HTML();

		$values = array();
		if($update)
			$values = $this->fromDbToSession();
		$pString = $error;
		$this->template->setVar('heading', $this->messages->text("heading", "configure"));
		$pString .= FORM::formHeader("adminConfigure");
		if($update)
			$pString .= FORM::hidden("update", "TRUE");
// Only for superadmin who is always userid = 1
		if(!$session->issetVar('setup_userId') || ($session->getVar('setup_userId') == 1))
		{
			array_key_exists("username", $values) ?
				$input = $values["username"] : $input = FALSE;
			$pString .= FORM::textInput($this->messages->text("config", "superUsername"),
				"username", $input, 30) . " " . MISC::span('*', 'required');
			$pString .= MISC::p();
			array_key_exists("password", $values) ?
				$input = $values["password"] : $input = FALSE;
			$pString .= FORM::passwordInput($this->messages->text("config", "superPassword"),
				"password", $input, 30) . " " . MISC::span('*', 'required');
			$pString .= MISC::p();
		}
		array_key_exists("fileDeleteSeconds", $values) ?
			$input = $values["fileDeleteSeconds"] : $input = 3600;
		$pString .= FORM::textInput($this->messages->text("config", "deleteSeconds"),
			"fileDeleteSeconds", $input, 10, 10) . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("paging", $values) ?
			$input = $values["paging"] : $input = 20;
		$pString .= FORM::textInput($this->messages->text("config", "paging"), "paging", $input, 10, 10) . 
			MISC::br() . $this->messages->text("hint", "pagingLimit") . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("pagingMaxLinks", $values) ?
			$input = $values["pagingMaxLinks"] : $input = 11;
		$pString .= FORM::textInput($this->messages->text("config", "maxPaging"),
			"pagingMaxLinks", $input, 10, 10) . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("stringLimit", $values) ?
			$input = $values["stringLimit"] : $input = 40;
		$pString .= FORM::textInput($this->messages->text("config", "stringLimit"),
			"stringLimit", $input, 10, 10) . 
			MISC::br() . $this->messages->text("hint", "pagingLimit") . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("imgWidthLimit", $values) ?
			$input = $values["imgWidthLimit"] : $input = 400;
		$pString .= FORM::textInput($this->messages->text("config", "imgWidthLimit"),
			"imgWidthLimit", $input, 10, 10) . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("imgHeightLimit", $values) ?
			$input = $values["imgHeightLimit"] : $input = 400;
		$pString .= FORM::textInput($this->messages->text("config", "imgHeightLimit"),
			"imgHeightLimit", $input, 10, 10) . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("maxPaste", $values) ?
			$input = $values["maxPaste"] : $input = 10;
		$pString .= FORM::textInput($this->messages->text("config", "maxPaste"),
			"maxPaste", $input, 10, 10) . MISC::span('*', 'required');
		$pString .= MISC::p();
		if(array_key_exists("lastChangesType", $values) && ($values["lastChangesType"] == 'N')) // set number
			$input = 1;
		else // Set no. days
			$input = 2;
		$array = array(1 => $this->messages->text("config", "lastChanges2"), 
			2 => $this->messages->text("config", "lastChanges3"));
		$pString .= FORM::selectedBoxValue($this->messages->text("config", "lastChanges1") , "lastChangesType", 
			$array, $input, 2, 80) . "&nbsp;&nbsp;";
		array_key_exists("lastChanges", $values) ?
			$input = $values["lastChanges"] : $input = 10;
		$pString .= FORM::textInput(FALSE, "lastChanges", $input, 10, 10) . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("lastChangesDayLimit", $values) ?
			$input = $values["lastChangesDayLimit"] : $input = 10;
		$pString .= FORM::textInput($this->messages->text("config", "lastChanges4"), 
			"lastChangesDayLimit", $input, 10, 10) . MISC::span('*', 'required');
		$pString .= MISC::p();
		$templates = TEMPLATE::loadDir();
		array_key_exists("template", $values) ?
			$input = $values["template"] : $input = "default";
		$pString .= FORM::selectedBoxValue($this->messages->text("config", "template") , "template", 
			$templates, $input) . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		include_once("core/messages/LOADLANGUAGE.php");
		$languages = LOADLANGUAGE::loadDir();
		array_key_exists("language", $values) ?
			$input = $values["language"] : $input = "en";
		$pString .= FORM::selectedBoxValue($this->messages->text("config", "language") , "language", 
			$languages, $input) . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		include_once("core/styles/LOADSTYLE.php");
		$styles = LOADSTYLE::loadDir("styles/bibliography");
// fetch array key name at element 0 in case we are running for first time
		$keys = array_keys($styles);
		array_key_exists("style", $values) ? 
			$input = $values["style"] : $input = $keys[0];
		$pString .= FORM::selectedBoxValue($this->messages->text("config", "style") , "style", 
				$styles, $input, 4) . " " . MISC::span('*', 'required');
		$pString .= MISC::p();
		array_key_exists("title", $values) ?
			$input = $values["title"] : $input = "WIKINDX";
		$pString .= FORM::textInput($this->messages->text("config", "title"), "title", $input, 30);
		$pString .= MISC::p();
		array_key_exists("contactEmail", $values) ?
			$input = $values["contactEmail"] : $input = FALSE;
		$pString .= FORM::textInput($this->messages->text("config", "email"), "contactEmail", $input, 30);
		$pString .= MISC::p();
		array_key_exists("description", $values) ?
			$input = $values["description"] : $input = FALSE;
		$pString .= FORM::textareaInput($this->messages->text("config", "description"),
			"description", $input, 75, 15) . 
				MISC::br() . $this->messages->text("hint", "format");
		$pString .= MISC::p();
		array_key_exists("multiUser", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "multiUser"), "multiUser", $input);
		$pString .= MISC::p();
		array_key_exists("userRegistration", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "userRegistration"), 
				"userRegistration", $input) . 
				MISC::br() . $this->messages->text("hint", "userRegistration");
		$pString .= MISC::p();
		array_key_exists("registrationModerate", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "registrationModerate"), 
				"registrationModerate", $input) . 
				MISC::br() . $this->messages->text("hint", "userRegistration");
		$pString .= MISC::p();
		array_key_exists("emailNewRegistrations", $values) ?
			$input = $values["emailNewRegistrations"] : $input = FALSE;
		$pString .= FORM::textInput($this->messages->text("config", "emailNewRegistrations"), 
			"emailNewRegistrations", $input, 30) . 
			MISC::br() . $this->messages->text("hint", "userRegistration");
		$pString .= MISC::p();
		array_key_exists("notify", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "notify"), "notify", $input) . 
				MISC::br() . $this->messages->text("hint", "userRegistration");
		$pString .= MISC::p();
		array_key_exists("fileAttach", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "fileAttach"), "fileAttach", $input);
		$pString .= MISC::p();
		array_key_exists("fileViewLoggedOnOnly", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "fileViewLoggedOnOnly"), 
			"fileViewLoggedOnOnly", $input);
		$pString .= MISC::p();
		array_key_exists("importBib", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "importBib"), 
			"importBib", $input);
		$pString .= MISC::p();
		array_key_exists("emailNews", $values) ?
			$input = "CHECKED" : $input = FALSE;
		$pString .= FORM::checkbox($this->messages->text("config", "emailNews"), "emailNews", $input) . 
			MISC::br() . $this->messages->text("hint", "userRegistration");
		$pString .= MISC::p(FORM::formSubmit(), FALSE, "right");
		$pString .= FORM::formEnd();
		$this->template->setVar('body', $pString);
		return $this->template->process();
	}

// write configuration details to WKX_config table, WKX_users and WKX_user_preferences
	function write(&$vars, $update = FALSE)
	{
		$this->checkInput($vars, $update);
// If we get here, we're cleared to write to the database.
// username and password.  USER::writeUser returns an error message if it fails, FALSE if it succeeds.
		include_once("core/user/USER.php");
		$user = new USER($this->db, $vars);
		include_once("core/session/SESSION.php");
		$session = new SESSION();
// Only for superadmin who is always userid = 1
		if(!$session->issetVar('setup_userId') || ($session->getVar('setup_userId') == 1))
		{
			if($update)
			{
				if($error = $user->writeUser(FALSE, 1))
					$this->badInput($error, $update);
				$user->writePreferences(1, FALSE);
			}
			else
			{
				if($error = $user->writeUser(TRUE, 1))
					$this->badInput($error, $update);
			}
		}
// Write default preferences (TRUE == insert).  This user is always id = 1
		include_once("core/html/HTML.php");
		$html = new HTML();
		foreach($this->fields as $field)
		{
			if(!array_key_exists($field, $vars))
			{
// Checkboxes
				if((($field == 'multiUser') || ($field == "userRegistration") || ($field == "notify")
				|| ($field == "fileAttach") || ($field == "fileViewLoggedOnOnly") 
				|| ($field == "importBib")|| ($field == "emailNews") || ($field == "registrationModerate")) && $update)
					$updateArray[$field] = 'N';
				continue;
			}
// Description is a textarea so leave NL reduction until display.
			if($field == 'description')
			{
				$value = $vars[$field];
				if(!trim($value))
					$nulls[] = $field;
			}
			else
			{
				$value = $html->removeNl($vars[$field]);
				if(($field == 'contactEmail') || ($field == "emailNewRegistrations"))
				{
					if(!trim($value))
						$nulls[] = $field;
				}
				if(($field == "registrationModerate") && array_key_exists('emailNewRegistrations', $vars) && 
					!trim($vars['emailNewRegistrations']))
				{
					if(!$update)
					{
						$valueArray[] = "N";
						$fieldArray[] = $field;
					}
					else
						$updateArray[$field] = "N";
					$session->delVar('config_registrationModerate');
					$session->delVar('setup_registrationModerate');
					continue;
				}
				if($field == 'lastChangesType')
				{
					if($value == 2)	// Days
						$value = 'D';
					else	// Number
						$value = 'N';
				}
			}
			if(!$update && !$value)
				continue;
// Checkboxes
			if(($field == 'multiUser') || ($field == "userRegistration") || ($field == "notify")
				|| ($field == "fileAttach") || ($field == "fileViewLoggedOnOnly") || ($field == "importBib")
				|| ($field == "emailNews") || ($field == "registrationModerate"))
				$value = 'Y';
// Are we inserting the row?
			if(!$update)
			{
				$valueArray[] = "$value";
				$fieldArray[] = $field;
			}
			else
				$updateArray[$field] = "$value";
		}
		if(!$update)
			$this->db->insert('WKX_config', $fieldArray, $valueArray);
		else
		{
			$this->db->update('WKX_config', $updateArray);
			if(isset($nulls) && !empty($nulls))
				$this->db->updateNull('WKX_config', $nulls);
		}
// As template may have changed, create new template object.
		$this->template = new TEMPLATE('content');
// As language may have changed, we create a new MESSAGES and ERRORS objects.
		$this->messages = new MESSAGES();
		$success = new SUCCESS();
		$errors = new ERRORS();
                $this->template->setVar('heading', $this->messages->text("heading", "configure"));
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $this->displaySetup($success->text("config"), TRUE));
	}
// Check input
	function checkInput($vars, $update)
	{
		include_once("core/init/SYSTEMCHECK.php");
// Store in session first and remove unrequired session variables
		include_once("core/session/SESSION.php");
		$session = new SESSION();
		foreach($this->fields as $key)
		{
			if(array_key_exists($key, $vars))
			{
				if(($key == 'multiUser') || ($key == 'userRegistration') || ($key == "notify") 
					 || ($key == "fileAttach") || ($key == "fileViewLoggedOnOnly") || ($key == "importBib")
					 || ($key == "emailNews") || ($key == 'registrationModerate'))
					$array[$key] = 'Y';
				else if($key == 'lastChangesType')
				{
					if($vars[$key] == 2) // Over last few days
						$array[$key] = 'D';
					else // Set number
						$array[$key] = 'N';
				}
				else
					$array[$key] = $vars[$key];
			}
			else if(($key == 'multiUser') || ($key == 'userRegistration') || ($key == "notify") 
				|| ($key == "fileAttach") || ($key == "fileViewLoggedOnOnly") || ($key == "importBib")
				|| ($key == "emailNews") || ($key == 'registrationModerate'))
			{
				$array[$key] = 'N';
				$session->delVar("config_" . $key);
				$session->delVar("setup_" . $key);
			}
		}
		$session->writeArray($array, "config");
// Only for superadmin who is always userid = 1
		if(!$session->issetVar('setup_userId') || ($session->getVar('setup_userId') == 1))
			$required = array("fileDeleteSeconds", "username", "password", 
			"paging", "pagingMaxLinks", "stringLimit", "maxPaste", "lastChanges", "lastChangesType",
			"lastChangesDayLimit");
		else
			$required = array("fileDeleteSeconds", "paging", "pagingMaxLinks", 
			"stringLimit", "maxPaste", "lastChanges", "lastChangesType", "lastChangesDayLimit");
		foreach($required as $value)
		{
// 'lastChanges' and 'lastChangesDayLimit' can be 0
			if(($value == 'lastChanges') || ($value == 'lastChangesDayLimit'))
			{
				if(!array_key_exists($value, $vars) || (trim($vars[$value] == '')))
					$this->badInput($this->errors->text("inputError", "missing", " ($value) "), $update);
			}
			else if(!array_key_exists($value, $vars) || !trim($vars[$value]))
				$this->badInput($this->errors->text("inputError", "missing", " ($value) "), $update);
		}
		$isNum = array("fileDeleteSeconds", "paging", "pagingMaxLinks", "stringLimit", "imgWidthLimit", 
			"imgHeightLimit", "maxPaste", "lastChanges", "lastChangesDayLimit",);
		foreach($isNum as $value)
		{
			if(array_key_exists($value, $vars) && !is_numeric($vars[$value]))
				$this->badInput($this->errors->text("inputError", "nan", " ($value) "), $update);
		}
// write default variables to 'setup_xxxx' session variables
		SYSTEMCHECK::writeSession($array, $session);
	}
// Error handling
	function badInput($error, $update)
	{
		include_once("core/html/CLOSE.php");
		new CLOSE($this->db, $this->displaySetup($error, $update));
	}
// When updating, if the config variables are not in a session, grab from db table and write to session.
// Admin configuration session variables have prefix of 'config_'.
// Returns associative array: fieldnames => values.
	function fromDbToSession()
	{
		include_once("core/session/SESSION.php");
		$session = new SESSION();
		include_once("core/html/HTML.php");
		$html = new HTML();
		if(!$row = $session->getArray("config"))
		{
			$recordset = $this->db->select(array('WKX_config'), $this->fields);
			$row = $this->db->fetchRow($recordset);
			if(!$session->writeArray($row, "config"))
				print $this->errors->text("sessionError", "write");
		}
// MG 'multiUser' is a checkbox, too...
		if(array_key_exists("multiUser", $row) && ($row['multiUser'] == 'N'))
			unset($row['multiUser']);
// MG 'userRegistration' is a checkbox, too...
		if(array_key_exists("userRegistration", $row) && ($row['userRegistration'] == 'N'))
			unset($row['userRegistration']);
// MG 'registrationModerate' is a checkbox, too...
		if(array_key_exists("registrationModerate", $row) && ($row['registrationModerate'] == 'N'))
			unset($row['registrationModerate']);
// MG 'notify' is a checkbox, too...
		if(array_key_exists("notify", $row) && ($row['notify'] == 'N'))
			unset($row['notify']);
// MG 'fileAttach' is a checkbox, too...
		if(array_key_exists("fileAttach", $row) && ($row['fileAttach'] == 'N'))
			unset($row['fileAttach']);
// MG 'fileViewLoggedOnOnly' is a checkbox, too...
		if(array_key_exists("fileViewLoggedOnOnly", $row) && ($row['fileViewLoggedOnOnly'] == 'N'))
			unset($row['fileViewLoggedOnOnly']);
// MG 'importBib' is a checkbox, too...
		if(array_key_exists("importBib", $row) && ($row['importBib'] == 'N'))
			unset($row['importBib']);
// MG 'importBib' is a checkbox, too...
		if(array_key_exists("emailNews", $row) && ($row['emailNews'] == 'N'))
			unset($row['emailNews']);

// user id is stored in session if user has already logged on.
		if($userId = $session->getVar('setup_userId'))
		{
			$recordset = $this->db->select(array('WKX_users'), array('username', 'password', 
				'fullname', 'admin'), 
				" WHERE " . $this->db->formatField('id') . " = " . $this->db->tidyInput($userId));
			$rowT = $this->db->fetchRow($recordset);
			$row['username'] = $rowT['username'];
			$row['password'] = $rowT['password'];
		}
// 'lastChanges' can be 0 so may not exist if called from the session
		if(!$row['lastChanges'])
			$row['lastChanges'] = 0;
// 'lastChangesDayLimit' can be 0 so may not exist if called from the session
		if(!$row['lastChangesDayLimit'])
			$row['lastChangesDayLimit'] = 0;
// tidy up the $row elements for presentation to the browser. Since array_map has difficulties when the
// function name is actually a class method, we do it the long way around.
// Actually figured out how to use array_map - but too lazy to change (if it ain't broke - don't fix it!)
		foreach($row as $key => $value)
			$tidy[$key] = $html->dbToFormTidy($value);
		return $tidy;
	}
// failure - bomb out
	function failure($error)
	{
		$this->template->setVar("heading", $this->messages->text("heading", "configure"));
		include_once("core/html/CLOSE.php");
		$this->template->setVar('body', $error);
		new CLOSE($this->db, $this->template->process());
	}
}
?>
